package com.lanyou.esb.cook.proxy.redis.persistent.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.lanyou.esb.cook.proxy.entity.IfAlarm;
import com.lanyou.esb.cook.proxy.entity.IfAvgResTimes;
import com.lanyou.esb.cook.proxy.redis.persistent.base.BasePersistentRedis;
import com.lanyou.esb.cook.proxy.redis.proxy.impl.IfAvgResTimesJedisProxy;
import com.lanyou.esb.cook.proxy.redis.proxy.impl.IfAvgResTimesKeysJedisProxy;

/**
 * 持久化接口平均响应时间<br>
 * 描述：将REDIS中的接口平均响应时间转存到数据中
 *
 * @author Davey.wu
 */
public class IfAvgResTimesPersistentRedis extends
		BasePersistentRedis<IfAvgResTimes> {
	/** Redis操作代理 **/
	private IfAvgResTimesJedisProxy jedisProxy;
	/** Redis操作代理 **/
	private IfAvgResTimesKeysJedisProxy keysJedisProxy;

	private static SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yyyyMMddHH");

	public IfAvgResTimesPersistentRedis() {
		// 每30秒执行一次
		this.setCron("0 0/1 * * * ?");
		this.setName("IfAvgResTimesPersistentRedis");
		this.setGroup("IfAvgResTimesPersistentRedis");
		this.setJobClass(this.getClass());
	}

	@Override
	public void persistent() throws Exception {
		List<IfAvgResTimes> list = new ArrayList<>(this.getBatchAmount());
		list.clear();
		IfAvgResTimes object = null;
		String nowSection = dateFormat.format(new Date());
		while (true) {
			try {
				String key = keysJedisProxy.get();
				// 没有KEY，返回
				if (StringUtils.isBlank(key)) {
					break;
				}
				// 判断是否在之前时间区间内
				if (!isBeforeSection(key, nowSection)) {
					// 不是之前的时间区间，证明是当前的时间区间，统计未完成，将其返回给REDIS,本次持久化过程结束
					keysJedisProxy.reset(key);
					break;
				}
				Map<String, Object> group = jedisProxy.getGroup(key);
				if (group == null || group.isEmpty()) {
					continue;
				}
				object = (IfAvgResTimes) group.get(key);
				// 没有数据，查找一下元素
				if (object == null) {
					continue;
				}
				// 获取总响应时间
				String totalNum = (String) group.get(jedisProxy.getNumKey(key));
				// 请求总次数
				String totalReq = (String) group.get(jedisProxy
						.getTimesKey(key));
				float avg = avg(totalNum, totalReq);
				object.setAvgResTimes(avg);
				list.add(object);

				// 达到批量保存的数目，将数据保存到数据库
				if (list.size() >= this.getBatchAmount()) {
					getService().save(list);
					list.clear();
					continue;
				}

			} catch (Exception e) {
				// TODO 如果是将字符串转换成对象时出错，继续读后面的数据
				object = null;
			}
		}
		// 保存剩余的数据
		getService().save(list);
		list.clear();
	}

	/**
	 * 获取平均值
	 * 
	 * @param totalNum
	 *            :总时间
	 * @param totalTimes
	 *            ：总次数
	 * @return
	 */
	private float avg(String totalNum, String totalTimes) {
		try {
			float num = Float.parseFloat(totalNum);
			long times = Long.parseLong(totalTimes);
			return num / times;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0.0f;
	}

	/**
	 * 判断是否在当前区间之前
	 * 
	 * @param key
	 * @param nowSection
	 * @return
	 */
	private boolean isBeforeSection(String key, String nowSection) {
		if (StringUtils.isBlank(key)
				|| !key.contains(IfAvgResTimesJedisProxy.KEY_SEPARATOR)) {
			// 键值不对
			return true;
		}
		String[] keys = key.split(IfAvgResTimesJedisProxy.KEY_SEPARATOR);
		if (keys.length != 2) {
			return true;
		}
		if (keys[1].compareTo(nowSection) < 0) {
			return true;
		}
		return false;
	}

	public IfAvgResTimesJedisProxy getJedisProxy() {
		return jedisProxy;
	}

	public void setJedisProxy(IfAvgResTimesJedisProxy jedisProxy) {
		this.jedisProxy = jedisProxy;
	}

	public IfAvgResTimesKeysJedisProxy getKeysJedisProxy() {
		return keysJedisProxy;
	}

	public void setKeysJedisProxy(IfAvgResTimesKeysJedisProxy keysJedisProxy) {
		this.keysJedisProxy = keysJedisProxy;
	}

}
